/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package rs_GUI;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import pojos.Musicgenre;
import pojos.Playlist;
import pojos.Song;

/**
 *
 * @author KATERINA
 */
public class ListSong extends javax.swing.JPanel {
    private RadioStationParentFrame frame;
    private EntityManager em;
    private Playlist playlist3;
    private boolean cancelSave; //Είναι true αν έχουμε έρθει από μεταβολή, ενω
    private String f = "";
    private List<Song> sList = new ArrayList<>();
                                //το θέτουμε false αν έχουμε έρθει από εισαγωγή
    //private List<Song> sng =new ArrayList<>();
    
    /**
     * Creates new form ListSong_Katerina
     */
    public ListSong(RadioStationParentFrame frame, EntityManager em, Playlist playlist3, boolean cancelSave) {
        this.frame = frame;
        this.em = em;
        this.playlist3 = playlist3;
        this.cancelSave = cancelSave;
        initComponents();
        searchTextField.setText(f);
        
        //Ταξινόμηση της songList
        sortSongList();
    }
    
    //Ταξινόμηση της songList
    private void sortSongList(){
        Collections.sort(songList, new Comparator<Song>() {
            @Override 
            public int compare(Song s1, Song s2) {
                return s1.getTitle().compareTo(s2.getTitle());
            }
        });
    }
    
    //Φιλτράρισμα της λίστας τραγουδιών με βάση κάποιο κριτήριο αναζήτησης
    public void getSearchedSongs(){
        //Αδειάζουμε τη songList
        songList.clear();
        //Αδειάζουμε το ArrayList sList
        sList.clear();
        //Βάζουμε στο sList το αποτέλεσμα του songQuery
        sList.addAll(songQuery.getResultList());
        boolean t = false;
        boolean a = false;
        boolean g = false;
        //Ελέγχουμε ένα ένα τα τραγούδια που περιέχονται στο sList
        //και αν πληρούν τα κριτήρια αναζήτησης τα προσθέτουμε στην songList
        for(Song s2 : sList){
            if(s2.getTitle().toLowerCase().contains(f.toLowerCase())){
                t=true;
            }
            if(s2.getAlbumid().getArtistid()!=null){
                if(s2.getAlbumid().getArtistid().getArtisticname().toLowerCase().contains(f.toLowerCase())){
                a=true;
                }
            }
            if(s2.getAlbumid().getMusicgroupid()!=null){
                if(s2.getAlbumid().getMusicgroupid().getName().toLowerCase().contains(f.toLowerCase())){
                g=true;
                }
            }
            if(t||a||g){
                songList.add(s2);
                t=false;
                a=false;
                g=false;
            }
        }
        //Μήνυμα για μη εύρεση αποτελεσμάτων
        if(songList.isEmpty()){
            JOptionPane.showMessageDialog(this, "Δεν βρέθηκαν αποτελέσματα", "",
                JOptionPane.WARNING_MESSAGE);
            songList.addAll(songQuery.getResultList());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        playlist1 = playlist3;
        songQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT s FROM Song s");
        songList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(songQuery.getResultList());
        mainLabel = new javax.swing.JLabel();
        searchTextField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        songTable = new javax.swing.JTable();
        okButton = new javax.swing.JButton();
        searchLabel = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();

        addHierarchyListener(new java.awt.event.HierarchyListener() {
            public void hierarchyChanged(java.awt.event.HierarchyEvent evt) {
                formHierarchyChanged(evt);
            }
        });

        mainLabel.setText("Επιλέξτε ένα τραγούδι από τη λίστα");

        searchTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchTextFieldActionPerformed(evt);
            }
        });
        searchTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                searchTextFieldKeyPressed(evt);
            }
        });

        searchButton.setText("ΑΝΑΖΗΤΗΣΗ");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        songTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        songTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, songList, songTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${title}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumid.artistid}"));
        columnBinding.setColumnName("Καλλιτέχνης");
        columnBinding.setColumnClass(pojos.Artist.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumid.musicgroupid}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(pojos.Musicgroup.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${duration}"));
        columnBinding.setColumnName("Διάρκεια(sec)");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        songTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                songTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(songTable);
        if (songTable.getColumnModel().getColumnCount() > 0) {
            songTable.getColumnModel().getColumn(3).setPreferredWidth(0);
        }

        okButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        searchLabel.setText("Κριτήριο αναζήτησης:");

        cancelButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelButton.setForeground(new java.awt.Color(204, 0, 0));
        cancelButton.setText("ΑΚΥΡΩΣΗ");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(193, 193, 193)
                                .addComponent(mainLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(70, 70, 70)
                                .addComponent(searchLabel)
                                .addGap(18, 18, 18)
                                .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(searchButton)))
                        .addGap(0, 76, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(258, 258, 258)
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton)
                    .addComponent(searchLabel))
                .addGap(23, 23, 23)
                .addComponent(mainLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void formHierarchyChanged(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formHierarchyChanged
        
    }//GEN-LAST:event_formHierarchyChanged

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        int row = songTable.getSelectedRow();
        
        // Έλεγχος για το αν έχει επιλεχθεί τραγούδι
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "Δεν έχει επιλεχθεί τραγούδι", "Σφάλμα",
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        //Έλεγχος για το αν το τραγούδι υπάρχει ήδη στη λίστα
        Song s = songList.get(row);
        if(playlist3.getSongList().contains(s)){
            JOptionPane.showMessageDialog(this, "Το τραγούδι:\n"+s+"\nυπάρχει ήδη στη λίστα:\n"+playlist3.getName(), "Σφάλμα",
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        //Βάλε στο playlist3 το τραγούδι
        playlist3.getSongList().add(s);
        
        //Επαναφορά του γονέα
        frame.addPanelInMain(new PlayListManagement(frame, em, playlist3, cancelSave));
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        //Επαναφορά του γονέα
        frame.addPanelInMain(new PlayListManagement(frame, em, playlist3, cancelSave));
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        f = searchTextField.getText();
        if(!((f=="")||(f.isEmpty()))){
            getSearchedSongs();
        }
        else{
            f="";
            getSearchedSongs();
        }
    }//GEN-LAST:event_searchButtonActionPerformed

    private void searchTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTextFieldActionPerformed
        
    }//GEN-LAST:event_searchTextFieldActionPerformed

    private void searchTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTextFieldKeyPressed
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
            f = searchTextField.getText();
            if(!((f=="")||(f.isEmpty()))){
                getSearchedSongs();
            }
            else{
                f="";
                getSearchedSongs();
            }
        }
    }//GEN-LAST:event_searchTextFieldKeyPressed

    private void songTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_songTableMouseClicked
        if(evt.getClickCount()==2){
            ActionEvent e = null;
            okButtonActionPerformed(e);
        }
    }//GEN-LAST:event_songTableMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel mainLabel;
    private javax.swing.JButton okButton;
    private pojos.Playlist playlist1;
    private javax.swing.JButton searchButton;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JTextField searchTextField;
    private java.util.List<pojos.Song> songList;
    private javax.persistence.Query songQuery;
    private javax.swing.JTable songTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
